package com.tool.lock.sema;

import java.util.concurrent.Semaphore;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2025/7/1 15:33
 * AB生成产品，最多5件，C消耗一个A和B
 */
public class SemaTest {
    private Semaphore semaphoreA = new Semaphore(5);
    private Semaphore semaphoreB = new Semaphore(5);
    private Semaphore semaphoreC = new Semaphore(0);


    public static void main(String[] args) {
        SemaTest semaTest = new SemaTest();

        Thread t1 = new Thread(() -> {
            semaTest.printA();
        });
        Thread t2 = new Thread(() -> {
            semaTest.printB();
        });
        Thread t3 = new Thread(() -> {
            semaTest.printC();
        });

        t1.start();
        t2.start();
        t3.start();
    }

    public void printA() {
        while (true) {
            try {
                semaphoreA.acquire();
                System.out.println("A生产");
                semaphoreC.release();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void printB() {
        while (true) {
            try {
                semaphoreB.acquire();
                System.out.println("B生产");
                semaphoreC.release();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void printC() {
        while (true) {
            try {
                semaphoreC.acquire();
                semaphoreA.release();
                semaphoreB.release();
                System.out.println("C消费");
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
